<?php
/**
 * Description: 获取签名后的
 *
 * @author      Eden
 * @datetime    2017/1/2 19:32
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */
require_once FCPATH . '/application/third_party/wechat/include.php';

class Sign_Model extends API_Model
{

    private $types = ['alipay', 'wechat'];

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param array $params
     */
    public function run($params = array())
    {

        $send['state'] = false;

        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $orders = $this->getOrder($params['sn']);

            if (empty($orders)) {
                $send['error'] = '订单不存在';
                break;
            }

            $type = $params['payType'];
            if ($sign = $this->$type($orders, $params)) {
                $send['state'] = true;
                $send['data'] = [
                    'type' => $type,
                    'sign' => $sign
                ];
            } else {
                $send['error'] = '无法获取支付签名';
            }

        } while(false);

        $this->output->send($send);
    }

    /**
     * 微信支付签名
     * @param $order
     * @return bool
     */
    private function wechat($orders, $params)
    {
        $wechat = new \Wechat\WechatPay();

        $wechat->appid = WX_APPID;          // wx_app_appid
        $wechat->mch_id =  WX_MCHID;
        $wechat->partnerKey = WX_APIKEY;
        $notifyUrl = rtrim(APP_URL, '/') . '/wechat/notify';
        file_put_contents("/tmp/w.log", var_export($orders, true) . PHP_EOL, FILE_APPEND);

        $totalPrice = 0;
        $balance = 0;
        $userid = 0;
        foreach ($orders as $order) {
            $totalPrice += intval($order['totalPrice']);
            $balance = intval($order['balancePrice']);
            $userid = intval($order['userId']);
        }

        if ($balance == $totalPrice) {
            $this->setError('金额不符，支付失败');
            return false;
        }

        $res = $wechat->getPrepayId('', '丘丘谷商品订单', $params['sn'], $totalPrice, $notifyUrl, 'APP', '订单编号:' . $params['sn']);
        if ($res) {
            /*
            $this->load->model('common/Pay_Model', 'pay');
            $this->pay->saveWxAppBuy([
                'out_trade_no' => $params['sn'],
                'prepayid' => $res,
                'total_fee' => $totalPrice,
                'userid' => $userid,
            ]);
            */

            $time = time();
            $output['appid'] = WX_APPID;
            $output['partnerid'] = WX_MCHID;
            $output['prepayid'] = $res;
            $output['noncestr'] = \Wechat\Lib\Tools::createNoncestr();
            $output['timestamp'] = "{$time}";
            $output['package'] = "Sign=WXPay";
            $output['sign'] = \Wechat\Lib\Tools::getPaySign($output, WX_APIKEY);
            $output['packagevalue'] = $output['package'];
            unset($output['package']);

            return $output;
        } else {
            $this->setError('预支付订单创建失败');
        }

        return false;
    }

    /**
     * 获取阿里支付的签名
     * @param $order
     * @return bool|string
     */
    private function alipay($orders, $params)
    {
        $totalPrice = 0;
        foreach ($orders as $order) {
            $totalPrice += intval($order['totalPrice']);
        }

        try {
            return alipay_sign([
                'subject' => '订单编号:' . $params['sn'],
                'body' => '丘丘谷商城订单',
                'out_trade_no' => $params['sn'],
                'total_amount' => doubleval($totalPrice / 100)
            ]);
        } catch(Exception $e) {
            $this->setError($e->getMessage());
        }
    }

    /**
     * 获取订单
     * @param $sn
     * @return mixed
     */
    private function getOrder($sn)
    {
        $db = clone($this->db);
        $q = $db->get_where('user_order', ['uuid' => $sn]);
        return $q->result_array();
    }

    /**
     *
     * @param $params
     * @return bool
     */
    private function checkParams($params)
    {
        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($params['payType']) || !in_array($params['payType'], $this->types)) {
            $this->setError('不支持的支付类型');
            return false;
        }

        if (empty($params['sn'])) {
            $this->setError('无此订单信息');
            return false;
        }

        return true;
    }
}
